package cn.byapps.hw.controller;

import cn.byapps.hw.entity.Student;
import cn.byapps.hw.service.StudentService;
import cn.byapps.hw.utils.execl.PoiExcelTest;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/uploadAnddownload")
public class UploadAndDownloadController {

    @Resource
    private StudentService studentService;

    @PostMapping("/multiUpload")
    public String multiUpload(@RequestParam(value = "clazzId") String clazzId, HttpServletRequest request) throws FileNotFoundException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) {
            path = new File("");
        }
        //存放地址
        File upload = new File(path.getAbsolutePath(), "static/upload/");
        if (!upload.exists()) {
            upload.mkdirs();
        }
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                return "上传第" + (i++) + "个文件失败";
            }
            //获取原文件名
            String fileName = file.getOriginalFilename();
            //分割文件名
            String[] fileNames = fileName.split("\\.");
            //格式化时间
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String dt = simpleDateFormat.format(date);
            //把时间放入文件名中
            fileName = fileNames[0] + dt + "." + fileNames[1];
            // 存储目录及名称
            String url_path = "upload" + File.separator + fileName;
            //图片保存路径
            String savePath = upload.getPath() + File.separator + url_path;
            System.out.println("保存地址：" + savePath);
            // 访问路径=静态资源路径+文件目录路径
            String visitPath = "static/" + url_path;
            System.out.println("访问uri：" + visitPath);

            File saveFile = new File(savePath);
            if (!saveFile.exists()) {
                saveFile.mkdirs();
            }
            try {
                //复制文件
                file.transferTo(saveFile);
            } catch (IOException e) {
                return "上传第" + (i++) + "个文件失败";
            }
            if (saveFile.exists()) {
                List list = PoiExcelTest.testReadExcel(saveFile.getAbsolutePath(), 0);
                List<Student> students = new ArrayList<>();
                for (int j = 1; j < list.size(); j++) {
                    List list1 = (List) list.get(j);
                    Student student = new Student((String) list1.get(0), (String) list1.get(1), (String) list1.get(3), (String) list1.get(2), null);
                    students.add(student);
                }
                saveFile.delete();
                System.out.println("删除成功");
                studentService.batchAdd(students, Integer.parseInt(clazzId));
            }
        }
        return "上传成功";
    }

    @RequestMapping("/download")
    public void downloadExcel(HttpServletResponse response, HttpServletRequest request) {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/static/temp/demo.xls");
            // 读到流中
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("demo.xls", "UTF-8"));
            // 循环取出流中的数据
            byte[] b = new byte[200];
            int len;

            while ((len = inputStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
